const { json } = require('express')
let express = require('express')
let fs = require('fs')
let path = require('path')
let jwt = require('jsonwebtoken')

let userRouter = express.Router()

// 注册
userRouter.post('/register', (req, res) => {
    let { phone, pass } = req.body
console.log(111);
    // 读取
    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let i = arr.findIndex((item) => {
        return item.phone == phone
    })
    if (i == -1) {
        arr.push({ ...req.body, pass: pass })
        // 写入
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8')

    } else {
        res.send({ code: 400, msg: '该手机号已注册，注册失败' })
    }

})
// 登录
userRouter.post('/login', (req, res) => {
    let { phone,pass } = req.body

    // 读取
    let filepath = path.join(__dirname, '../json/users.json')
    let arr = fs.readFileSync(filepath)
    arr = arr.toString() ? JSON.parse(arr) : []

    let i = arr.findIndex((item) => {
        return item.phone == phone && item.pass == pass
    })
    if (i != -1) {
        let token = jwt.sign({ phone }, '1234', { algorithm: 'HS256', expiresIn: 60 })
        res.send({ code: 200, msg: '登陆成功', userinfo: arr[i],token })
    } else {
        res.send({ code: 400, msg: '登陆失败' })
    }

})

module.exports = userRouter